package com.example.transation.txlcncommon.bean;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import lombok.Data;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * 通用返回类
 *
 * @author luojm
 * 2019-11-22 15:24:58
 */
@JsonInclude(Include.NON_NULL)
@Data
public class Result<T> {

    private Integer code = ResultCode.SUCCESS.getCode();
    private String msg = "成功";
    private T data;
    private String timestamp = String.valueOf(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")));

    public Result() {
    }

    public Result(ResultCode codeEnum, String msg, T data) {
        this.code = codeEnum.getCode();
        this.msg = msg;
        this.data = data;
    }

    public Result(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static <T> Result<T> create() {
        return new Result<T>();
    }

    public static <T> Result<T> success(String message, T data) {
        return new Result<T>(ResultCode.SUCCESS, message, data);
    }

    public static <T> Result<T> success() {
        Result<T> response = create();
        response.setCode(ResultCode.SUCCESS.getCode());
        return response;
    }

    public static <T> Result<T> success(T data) {
        Result<T> response = create();
        response.setData(data);
        response.setCode(ResultCode.SUCCESS.getCode());
        return response;
    }

    public Result<T> code(int code){
        this.code = code;
        return this;
    }

    public Result<T> msg(String msg){
        this.msg = msg;
        return this;
    }

    public Result<T> msg(T data){
        this.data = data;
        return this;
    }

    public static <T> Result<T> fail(ResultCode codeEnum, String message, T data) {
        return new Result<T>(codeEnum, message, data);
    }

    public static <T> Result<T> fail(ResultCode codeEnum, String message) {
        return new Result<T>(codeEnum, message, null);
    }

    public static <T> Result<T> fail(int code, String message) {
        return new Result<T>(code, message, null);
    }

    public static <T> Result<T> fail() {
        return new Result<T>(ResultCode.FAIL, "业务处理失败!", null);
    }

    public static <T> Result<T> fail(String message) {
        return new Result<T>(ResultCode.FAIL, message, null);
    }

    public static <T> Result<T> failParam() {
        return new Result<T>(ResultCode.FAIL, ResultCode.PARAMERROR.getMsg(), null);
    }

}
